#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render, redirect, HttpResponse
from app01 import models
from app01.forms.notice import NoticeModelForm, NoticeUserModelForm
from rbac.service.urls import memory_reverse
from django.db.models import Q
from rbac.utils.pagination import Pagination


def notice_list(request):
    """
    用户列表
    :param request:
    :return:
    """
    # ########## 1. 批量操作 ##########
    action_dict = {'action_multi_delete': '批量删除', 'action_multi_add': '批量导入'}

    if request.method == 'POST':
        action_func_name = request.POST.get('action')
        """批量删除"""
        if action_func_name == "action_multi_delete":
            pk_list = request.POST.getlist('pk')
            print(action_func_name, pk_list)
            models.Notice.objects.filter(id__in=pk_list).delete()
        elif action_func_name == "action_multi_add":
            print('批量导入')
            return redirect('/customer/import/')

    # ########## 1. 关键字搜索功能 ##########
    # search_list = ['title', 'author__name']
    search_list = ['title__contains', 'author__name__contains']
    search_value = request.GET.get('q', '')
    conn = Q()
    conn.connector = 'OR'
    # conn.children.append(('title', search_value))
    if search_value:
        for item in search_list:
            conn.children.append((item, search_value))
    # ########## 2. 按字段排序功能 ##########
    # order_list = ['name']
    order_list = []

    # notice_queryset = models.Notice.objects.all()
    notice_queryset = models.Notice.objects.filter(conn).order_by(*order_list)

    # ########## 3. 处理分页 ##########
    all_count = notice_queryset.count()
    query_params = request.GET.copy()
    query_params._mutable = True

    pager = Pagination(
        current_page=request.GET.get('page'),
        all_count=all_count,
        base_url=request.path_info,
        query_params=query_params,
        per_page=3,
    )

    notice_queryset = notice_queryset[pager.start:pager.end]

    return render(request, 'notice_list.html',
                  {
                      'notice_queryset': notice_queryset,
                      'search_list': search_list,
                      'search_value': search_value,
                      'pager': pager,
                      'action_dict': action_dict,
                  })


def notice_add(request):
    """
    添加消息
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = NoticeUserModelForm()
        return render(request, 'notice_add.html', {'form': form})

    form = NoticeUserModelForm(data=request.POST)

    user_id = request.session.get('user_id')
    author = models.UserInfo.objects.filter(id=user_id).first()

    if form.is_valid():
        form.instance.author = author
        form.save()
        return redirect(memory_reverse(request, 'notice_list'))

    return render(request, 'notice_add.html', {'form': form})


def notice_edit(request, pk):
    """
       编辑用户
       :param request:
       :param pk: 要修改的用户ID
       :return:
       """
    obj = models.Notice.objects.filter(id=pk).first()
    if not obj:
        return HttpResponse('用户不存在')
    if request.method == 'GET':
        form = NoticeModelForm(instance=obj)
        return render(request, 'rbac/change.html', {'form': form})

    form = NoticeModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(memory_reverse(request, 'notice_list'))

    return render(request, 'rbac/change.html', {'form': form})


def notice_del(request, pk):
    """
    删除用户
    :param request:
    :param pk:
    :return:
    """
    origin_url = memory_reverse(request, 'notice_list')
    if request.method == 'GET':
        return render(request, 'rbac/delete.html', {'cancel': origin_url})

    models.Notice.objects.filter(id=pk).delete()
    return redirect(origin_url)


def notice_info(request, pk):
    notice_object = models.Notice.objects.filter(id=pk).first()
    return render(request, 'notice_info.html', {'notice_object': notice_object})